package org.biouno.unochoice;

import static hudson.Util.fixEmpty;
import static hudson.Util.fixEmptyAndTrim;

import com.alibaba.fastjson.JSONObject;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import hudson.EnvVars;
import hudson.Extension;
import hudson.Util;
import hudson.model.*;
import hudson.model.Queue;
import hudson.model.queue.Tasks;
import hudson.plugins.git.GitException;
import hudson.plugins.git.GitTool;
import hudson.security.ACL;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;

import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;

import jenkins.model.Jenkins;
import jenkins.security.FIPS140;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.transport.RemoteConfig;
import org.jenkinsci.plugins.gitclient.Git;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.jenkinsci.plugins.gitclient.GitURIRequirementsBuilder;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ExportedBean
public class WorkspaceConfig
        extends AbstractDescribableImpl<WorkspaceConfig> implements Serializable {
    private static final Logger log =
            LoggerFactory.getLogger(WorkspaceConfig.class);

    private List<UserRemoteConfig> userRemoteConfigs;
    private List<BuildConfig> buildConfigs;
    private String name;
    private String workPath;

    @DataBoundConstructor
    public WorkspaceConfig(List<UserRemoteConfig> userRemoteConfigs,
                           List<BuildConfig> buildConfigs, @CheckForNull String name,
                           String workPath) {
        this.userRemoteConfigs = userRemoteConfigs;
        this.buildConfigs = buildConfigs;
        this.name = name;
        if (name.length() == 0 && userRemoteConfigs.size() > 0) this.name = userRemoteConfigs.get(0).getRepositoryName();
        this.workPath = workPath.length() == 0 ? "src" : workPath;
    }

    public JSONObject toJSONObject() {
        JSONObject jsonObject = new JSONObject();
        List<JSONObject> builds = new ArrayList<>();
        List<JSONObject> gitConfigs = new ArrayList<>();
        jsonObject.put("name", name);
        jsonObject.put("workPath", workPath);
        if (buildConfigs != null) {
            buildConfigs.forEach(item -> {
                builds.add(item.toJSONObject());
            });
        }
        if (userRemoteConfigs != null) {
            userRemoteConfigs.forEach(
                    item -> {
                        gitConfigs.add(item.toJSONObject());
                    });
        }
        jsonObject.put("gitConfig", gitConfigs);
        jsonObject.put("buildConfigs", builds);
        return jsonObject;
    }

    @Exported
    @Whitelisted
    public String getName() {
        return name;
    }

    @Exported
    @Whitelisted
    public List<UserRemoteConfig> getUserRemoteConfigs() {
        return userRemoteConfigs;
    }

    @Exported
    @Whitelisted
    public List<BuildConfig> getBuildConfigs() {
        return buildConfigs;
    }

    @Exported
    @Whitelisted
    public String getWorkPath() {
        return workPath;
    }

    @Override
    public String toString() {
        JSONObject jsonObject = new JSONObject();
        return jsonObject.toString();
    }

    private final static Pattern SCP_LIKE = Pattern.compile("(.*):(.*)");

    @Extension
    public static class DescriptorImpl extends Descriptor<WorkspaceConfig> {

        public static StandardCredentials
        lookupCredentials(@CheckForNull Item project, String credentialId,
                          String uri) {
            return (credentialId == null)
                    ? null
                    : CredentialsMatchers.firstOrNull(
                    CredentialsProvider.lookupCredentialsInItem(
                            StandardCredentials.class, project, ACL.SYSTEM2,
                            GitURIRequirementsBuilder.fromUri(uri).build()),
                    CredentialsMatchers.withId(credentialId));
        }

        @Override
        public String getDisplayName() {
            return "";
        }
    }
}
